home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 4852 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  2.2 KB

  1. Path: news.uni-jena.de!news
  2. From: mkt@isun04.inf.uni-jena.de (Tilo Koerbs)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: passing pointers to functions
  5. Date: 1 Feb 1996 11:28:02 GMT
  6. Organization: Lehrstuhl fuer Rechnerarchitektur- und kommunikation, FSU Jena
  7. Message-ID: <4eq842$fpu@fsuj01.rz.uni-jena.de>
  8. References: <Pine.A32.3.91.960131105301.69201A-100000@red.weeg.uiowa.edu>
  9. Reply-To: mkt@isun04.inf.uni-jena.de
  10. NNTP-Posting-Host: isun07.inf.uni-jena.de
  11.  
  12. > I want to pass an empty pointer to a function.  
  13. >   Inside the function, I create an array.  Then I set the 
  14. > pointer_to_array = &A[0].  Finally at the end of the function I return 
  15. > the pointer_to_array to my main.
  16. > void main ()
  17. > {
  18. >     int *A1 = NULL;
  19. >     A1 = MakeArray(A1);
  20. >     cout << "First element in Array is" << *A1;
  21. > }
  22. >   My specific question is: what should my function header look like?
  23. >   My general question is: what are the rules for passing (and returning) 
  24. > pointers to functions w/ call by reference,parameter, and constant reference?
  25.  
  26. Your questions are looking a little bit too general!
  27. I try to give some answers:
  28.  
  29. Your function will pass the argument and the return value by value.
  30.     int * MakeArray(int *);
  31. But what for do you use the argument in the function?
  32. If you always pass a so called NULL-pointer to the function, then it
  33. knows this fact already and needs no argument to tell it!
  34.     int * MakeArray() {
  35.         int * A = new int[10];
  36.         pointer_to_array = A;  // This is the same as: p_t_a = &A[0];
  37.             // An array is automatically converted to a pointer
  38.             // to its first argument!
  39.         return pointer_to_array;
  40.     }
  41.     // The whole function can be written as: return new int[10];  // Thats all!
  42.  
  43. To the general question:
  44.     You can pass anything (ints, pointers, ...) by value (the default).
  45.         So a copy of the object is created and then passed.
  46.     You can pass anything by reference (except that there are no references
  47.         on references). So a reference (a hidden pointer) to the object
  48.         is passed.
  49.         Example:
  50.             void MakeArray(int*& A) {  // A reference to a pointer.
  51.                 A = new int[10];  // The A given to the function is
  52.                           // manipulated.
  53.             }
  54.         This function works the same as the others.
  55.  
  56. I suggest you read a book for more details.
  57. Bye
  58.  
  59.  
  60.